/**
    Copyright (c) 2010 yakiimo02
    Distributed under the New BSD License.
    See included license.txt or http://www.yakiimo3d.com/NewBSDLicense.txt
**/

#include "DXUT.h"
#include "CaptureFrameBuffer.h"
#include "DXHelper.h"

#include <string>

CaptureFrameBuffer    g_captureFrameBuffer;

/**
*/
HRESULT CaptureFrameBuffer::Capture( const std::wstring& strFileName )
{
    HRESULT hr;

    ID3D11DeviceContext* pd3dImmediateContext = DXUTGetD3D11DeviceContext();
    IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain();
    
    ID3D11Texture2D* pSwapChainBuffer = 0;
    V_RETURN( pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), reinterpret_cast< void** >( &pSwapChainBuffer ) ) );

    // Save screenshot in same directory as executable.
    wchar_t buffer[ MAX_PATH ];
    int nLen = ::GetModuleFileName(NULL, buffer, MAX_PATH);
    if( nLen == 0 ) {
       return E_FAIL;
    }
    std::wstring strExeFullPath = buffer;

    std::wstring strOutFilePath = strExeFullPath.substr( 0, strExeFullPath.rfind( L"\\" )+1 ) + strFileName;

    V_RETURN( D3DX11SaveTextureToFile(
          pd3dImmediateContext,
          pSwapChainBuffer,
          D3DX11_IFF_BMP,
          strOutFilePath.c_str()
          ) );

    SAFE_RELEASE( pSwapChainBuffer );

    return hr;
}